'use client'

import React, { useRef } from 'react'
import { Upload, Download, FileSpreadsheet, FileText, Save } from 'lucide-react'
import { Sheet, Cell } from '@/types/sheet'
import * as XLSX from 'xlsx'

interface ImportExportToolbarProps {
  sheet: Sheet
  cells: Cell[]
  onImport?: (cells: Cell[]) => void
  onExport?: (format: 'csv' | 'excel') => void
  onSave?: (cells: Cell[]) => void
  className?: string
}

export const ImportExportToolbar: React.FC<ImportExportToolbarProps> = ({
  sheet,
  cells,
  onImport,
  onExport,
  onSave,
  className = ''
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 处理保存
  const handleSave = () => {
    if (onSave && cells.length > 0) {
      onSave(cells)
      console.log('保存表格数据:', cells.length, '个单元格')
    } else {
      console.log('没有数据需要保存')
    }
  }

  // 处理文件导入
  const handleImport = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    try {
      const cells = await parseFileToCells(file)
      onImport?.(cells)
      
      // 显示成功消息
      console.log('文件导入成功')
    } catch (error) {
      console.error('文件导入失败:', error)
      alert('文件导入失败，请检查文件格式')
    }

    // 清空input值，允许重复选择同一文件
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  // 解析文件为单元格数据
  const parseFileToCells = async (file: File): Promise<Cell[]> => {
    const extension = file.name.split('.').pop()?.toLowerCase()
    
    if (extension === 'csv') {
      return parseCSVFile(file)
    } else if (extension === 'xlsx' || extension === 'xls') {
      return parseExcelFile(file)
    } else {
      throw new Error('不支持的文件格式，请选择CSV或Excel文件')
    }
  }

  // 解析CSV文件
  const parseCSVFile = async (file: File): Promise<Cell[]> => {
    const text = await file.text()
    const lines = text.split('\n')
    const cells: Cell[] = []

    lines.forEach((line, rowIndex) => {
      if (line.trim()) {
        const values = line.split(',').map(v => v.trim().replace(/^"|"$/g, ''))
        values.forEach((value, colIndex) => {
          if (value) {
            cells.push({
              id: `${rowIndex}-${colIndex}`,
              sheetId: sheet.id,
              row: rowIndex,
              column: colIndex,
              value: value,
              style: undefined,
              createdAt: new Date(),
              updatedAt: new Date()
            })
          }
        })
      }
    })

    return cells
  }

  // 解析Excel文件
  const parseExcelFile = async (file: File): Promise<Cell[]> => {
    const cells: Cell[] = []
    
    try {
      // 读取文件内容
      const arrayBuffer = await file.arrayBuffer()
      
      // 解析Excel文件
      const workbook = XLSX.read(arrayBuffer, { type: 'array' })
      
      // 获取第一个工作表
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      
      // 转换为JSON格式
      const jsonData: any[][] = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) as any[][]
      
      // 转换为Cell格式
      jsonData.forEach((row: any[], rowIndex: number) => {
        row.forEach((value: any, colIndex: number) => {
          if (value !== null && value !== undefined && value !== '') {
            cells.push({
              id: `${rowIndex}-${colIndex}`,
              sheetId: sheet.id,
              row: rowIndex,
              column: colIndex,
              value: String(value),
              style: undefined,
              createdAt: new Date(),
              updatedAt: new Date()
            })
          }
        })
      })
      
      console.log('Excel文件解析成功，共解析', cells.length, '个单元格')
    } catch (error) {
      console.error('Excel文件解析失败:', error)
      throw new Error('Excel文件解析失败')
    }
    
    return cells
  }

  // 导出为CSV
  const handleExportCSV = () => {
    const csvContent = cellsToCSV(cells)
    downloadFile(csvContent, `${sheet.title || 'sheet'}.csv`, 'text/csv')
    onExport?.('csv')
  }

  // 导出为Excel
  const handleExportExcel = () => {
    try {
      // 创建新的工作簿
      const workbook = XLSX.utils.book_new()
      
      // 将单元格数据转换为二维数组
      const maxRow = Math.max(...cells.map(cell => cell.row), 0)
      const maxCol = Math.max(...cells.map(cell => cell.column), 0)
      
      const worksheetData: any[][] = []
      for (let row = 0; row <= maxRow; row++) {
        worksheetData[row] = []
        for (let col = 0; col <= maxCol; col++) {
          worksheetData[row][col] = ''
        }
      }
      
      // 填充数据
      cells.forEach(cell => {
        worksheetData[cell.row][cell.column] = cell.value || ''
      })
      
      // 创建工作表
      const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
      
      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
      
      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
      
      // 下载文件
      const blob = new Blob([excelBuffer], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `${sheet.title || 'sheet'}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      
      onExport?.('excel')
      console.log('Excel文件导出成功')
    } catch (error) {
      console.error('Excel文件导出失败:', error)
      alert('Excel文件导出失败')
    }
  }

  // 将单元格数据转换为CSV格式
  const cellsToCSV = (cells: Cell[]): string => {
    if (cells.length === 0) return ''

    // 找到最大行和列
    const maxRow = Math.max(...cells.map(cell => cell.row))
    const maxCol = Math.max(...cells.map(cell => cell.column))

    // 创建二维数组
    const grid: string[][] = []
    for (let row = 0; row <= maxRow; row++) {
      grid[row] = []
      for (let col = 0; col <= maxCol; col++) {
        grid[row][col] = ''
      }
    }

    // 填充数据
    cells.forEach(cell => {
      grid[cell.row][cell.column] = cell.value || ''
    })

    // 转换为CSV格式
    return grid.map(row => 
      row.map(cell => `"${cell.replace(/"/g, '""')}"`).join(',')
    ).join('\n')
  }

  // 下载文件
  const downloadFile = (content: string, filename: string, mimeType: string) => {
    const blob = new Blob([content], { type: mimeType })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  return (
    <div className={`flex items-center gap-2 ${className}`}>
      {/* 保存按钮 */}
      <button
        onClick={handleSave}
        className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
        title="保存表格数据"
        disabled={!onSave || cells.length === 0}
      >
        <Save className="w-4 h-4" />
        <span>保存</span>
      </button>

      {/* 导入按钮 */}
      <button
        onClick={() => fileInputRef.current?.click()}
        className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
        title="导入文件"
      >
        <Upload className="w-4 h-4" />
        <span>导入</span>
      </button>

      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept=".csv,.xlsx,.xls"
        onChange={handleImport}
        className="hidden"
      />

      {/* 导出CSV按钮 */}
      <button
        onClick={handleExportCSV}
        className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
        title="导出为CSV"
      >
        <FileText className="w-4 h-4" />
        <span>导出CSV</span>
      </button>

      {/* 导出Excel按钮 */}
      <button
        onClick={handleExportExcel}
        className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
        title="导出为Excel"
      >
        <FileSpreadsheet className="w-4 h-4" />
        <span>导出Excel</span>
      </button>
    </div>
  )
}
